package com.wg.gateway.filter;

import cn.hutool.core.collection.CollectionUtil;
import com.wg.common.constant.JwtClaimsConstant;
import com.wg.gateway.properties.AuthProperties;
import com.wg.gateway.properties.JwtProperties;
import com.wg.common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author zf_serveer
 * @CreateTime 2025/1/13 0013
 */
@Component
@RequiredArgsConstructor
//@EnableConfigurationProperties(JwtProperties.class)
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final JwtProperties jwtProperties;
    private final AuthProperties authProperties;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取Request
        ServerHttpRequest request = exchange.getRequest();
        // 2.判断是否不需要拦截
        if(isExclude(request.getPath().toString())){
            // 无需拦截，直接放行
            return chain.filter(exchange);
        }
        // 3.获取请求头中的token
        String token = null;
        List<String> headers = request.getHeaders().get(jwtProperties.getTokenName());
        if (!CollectionUtil.isEmpty(headers)) {
            token = headers.get(0);
        }
        // 4.校验并解析token
        Long userId = null;
        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
            userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
        } catch (Exception e) {
            // 如果无效，拦截
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            // 构建响应内容
            String errorMessage = "{\"code\": 0,\"msg\": \"Unauthorized\", \"data\": \"\"}";
            DataBufferFactory bufferFactory = response.bufferFactory();
            DataBuffer dataBuffer = bufferFactory.wrap(errorMessage.getBytes());

            // 发送响应体
            return response.writeWith(Mono.just(dataBuffer)).then(Mono.empty());
        }

        // 有效，传递用户信息
        System.out.println("userId = " + userId);
        String finalUserIdStr = userId.toString();
        ServerWebExchange ex = exchange.mutate().request(b -> b.header("user-info", finalUserIdStr)).build();
        // 6.放行
        return chain.filter(ex);
    }
    private boolean isExclude(String antPath) {
        for (String pathPattern : authProperties.getExcludePaths()) {
            if(antPathMatcher.match(pathPattern, antPath)){
                return true;
            }
        }
        return false;
    }
    @Override
    public int getOrder() {
        return 0;
    }
}
